package com.epidata.exam.dao;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.epidata.exam.model.Person;

public class BaseDao<T extends Person> {


	@Inject
	private EntityManager em;


	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

	protected void save(T entity){
		em.persist(entity);
	}


	protected List<T> getAll(Class<T> clazz) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<T> criteria = cb.createQuery(clazz);
		Root<T> entity = criteria.from(clazz);
		criteria.select(entity).orderBy(cb.asc(entity.get("name")));
		return em.createQuery(criteria).getResultList();
	}

	protected T findById(Class<T> clazz,Long id){
		return em.find(clazz,id);
	}

}
